package com.oocl.scp_ssh.scp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.oocl.scp_ssh.analyze.CommandAnalzyer;
import com.oocl.scp_ssh.controller.Controller;
import com.oocl.scp_ssh.controller.impl.LsController;
import com.oocl.scp_ssh.controller.impl.RmController;
import com.oocl.scp_ssh.controller.impl.ScpController;
import com.oocl.scp_ssh.pojo.Command;
import com.oocl.scp_ssh.pojo.impl.LsCommand;
import com.oocl.scp_ssh.pojo.impl.RmCommand;
import com.oocl.scp_ssh.pojo.impl.ScpMsg;
import com.oocl.scp_ssh.util.FileUtils;

public class Server {

	private ScpJudge scpJudge;
	private ServerSocket server;
	private String PATH = "upload/";
	
	private CommandAnalzyer commandAnalzyer;
	
	private static Server sInstance;
	private Server() throws IOException{
		this.scpJudge = new ScpJudge();
		this.server = new ServerSocket(8001);
		this.commandAnalzyer =new CommandAnalzyer();
	}
	
	public static Server getInstance() throws IOException{
		if(sInstance == null)
			synchronized (Server.class) {
				if(sInstance==null)
					sInstance = new Server();
			}
		return sInstance;
	}
	
	
	/**
	 * 启动
	 */
	public void start(){
		try {
			while(true) {
				
				Socket socket = server.accept();
				
				Controller controller = null;
				
				OutputStream out = socket.getOutputStream();
				InputStream in = socket.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				
				
				String  cmd = reader.readLine();
				System.out.println("从Client接收到： "+cmd);
				
				////解析cmd， 并构造目标文件
//				ScpMsg msg = this.scpJudge.judge(cmd);
				
				Command command = this.commandAnalzyer.analyzeCmd(cmd);
				
				if(command instanceof LsCommand) {
					//// LS 命令
					controller = new LsController((LsCommand)command);
				}else if(command instanceof RmCommand) {
					///// RM 命令
					controller = new RmController((RmCommand)command);
					
				}else if(command instanceof ScpMsg){
					////scp 命令
					controller = new ScpController((ScpMsg)command);
				}
				controller.dealWithClient(in, out);

			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 停止
	 */
	public void stop() {
		
	}
	
	
	public static void main(String[] args) throws IOException {
		Server.getInstance().start();
	}
	
}
